package com._21cn.cms.article.service;

import com._21cn.cms.article.Constants;
import com._21cn.cms.article.dao.ArticleContentDao;
import com._21cn.cms.article.dao.ArticleDao;
import com._21cn.cms.article.dao.ArticlePictureDao;
import com._21cn.cms.article.dao.ArticleThumbPictureDao;
import com._21cn.cms.article.entity.Article;
import com._21cn.cms.article.entity.ArticlePicture;
import com._21cn.cms.article.entity.ArticleThumbPicture;
import com._21cn.cms.resource.entity.Picture;
import com._21cn.cms.resource.utils.PictureUtil;
import com._21cn.cms.site.entity.Channel;
import com._21cn.cms.site.entity.Column;
import com._21cn.cms.site.entity.Site;
import com._21cn.cms.site.service.ChannelService;
import com._21cn.cms.site.service.ColumnService;
import com._21cn.cms.site.service.SiteService;
import com._21cn.framework.base.db.BaseDao;
import com._21cn.framework.base.service.impl.BaseServiceImpl;
import com._21cn.framework.flip.PageHashMap;
import com._21cn.framework.flip.PageList;
import com._21cn.framework.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;


@Service("articleService")
public class ArticleService extends BaseServiceImpl<Article> {
	
    @Autowired
    private ArticleDao articleDao;

    @Autowired
    private ArticleContentDao articleContentDao;

    @Autowired(required = false)
    private ArticlePictureDao articlePictureDao;

    @Autowired(required = false)
    private ArticleThumbPictureDao articleThumbPictureDao;

    @Autowired(required = false)
    private ColumnService columnService;

    @Autowired(required = false)
    private ChannelService channelService;

    @Autowired(required = false)
    private SiteService siteService;

    @Override
    protected BaseDao<Article> getBaseDao() {
        return articleDao;
    }

    public PageList getSearchArticleList(Map<String, Object> params, int pageNo, int pageSize, boolean doCount){
        return articleDao.selectByMapJoinColumn( params, pageNo, pageSize, doCount );
    }

    @Override
    public void insert( Article object ) {
        System.out.println("==========="+object.getArticleUrl());
        super.insert( object );                                     //插入文章
        if( object.getArticleType().equals(Constants.ARTICLE_TYPE_COMMON)) {
            object.regulateArticleUrl();                            //重新计算articleUrl
            super.update(object);
        }
        if( !StringUtil.isEmpty(object.getContent()) ){
            articleContentDao.insert(object);                     //插入内容
        }
        //插入文章图片
        insertArticlePictureList( object );
        //插入文章缩略图
        insertArticleThumbPicList( object );
    }

    @Override
    public int update( Article object ) {
        return update(object, true);
    }

    public int update( Article object, boolean  extraProperty) {
        int flag = super.update( object );
        if( extraProperty ){
            //更新内容
            Article articleContent = articleContentDao.selectById( object.getId() );
            if( articleContent!=null ){
                articleContentDao.update( object );
            }else {
                articleContentDao.insert( object );
            }
            //更新文章图片
            updateArticlePictureList( object );
            //更新文章缩略图
            updateArticleThumbPicList( object );
        }
        return flag;
    }

    @Override
    public Article getById( Object id ) {
        return getById( id, true );
    }

    public Article getById( Object id , boolean extraProperty) {
        Article article = super.getById( id );
        if( article == null ) {
            return null;
        }
        if( extraProperty ){
            loadSiteInfo(article);                                    //加载站点信息

            Article obj = articleContentDao.selectById(id);         //内容
            if( obj!=null ){
                article.setContent(obj.getContent());
            }
            //组图 and 缩略图
            Map<String, Object> param = new HashMap<String, Object>();
            param.put( "eqArticleId", id );
            article.setArticleThumbPictureList(articleThumbPictureDao.selectByMap( param, 1, 10, false ));
            if( article.getPicFlag().equals(Constants.PIC_FLAG_HAVE_PIC)){
                param.put("orderByClause", "ORDER_NUM asc");
                article.setArticlePictureList( articlePictureDao.selectByMap( param, 1, 1000, false ) );
            }
        }
        return article;
    }

    public Article loadSiteInfo( Article article){
        if( article.getColumn().getId()==0 ){                   //主栏目
            int columnId = article.getColumnId();
            Column column = columnService.getById(columnId);
            article.setColumn(column);
            article.setSite(column.getSite());
            article.setChannel(column.getChannel());
        }
        if( article.getChannel().getId()==0 ){                   //频道
            int channelId = article.getChannelId();
            Channel channel = channelService.getById(channelId);
            article.setChannel(channel);
        }
        if( article.getSite().getId()==0 ){                     //站点
            int siteId = article.getSiteId();
            Site site = siteService.getById(siteId);
            article.setSite(site);
        }
        return article;
    }

    public PageHashMap getMap(Map<String, Object> params, int pageNo, int pageSize, boolean doCount){
        return articleDao.selectMapByMap( params, pageNo, pageSize, doCount );
    }

    public PageList<Article> getListByIds(List<Integer> idList) {
        PageList result = new PageList();
        if (!idList.isEmpty()) {
            Map params = new HashMap();
            params.put("inIdList", idList);
            PageHashMap articleMap = getMap(params, 1, idList.size(), false);
            for (Integer articleId : idList) {
                Article article = (Article)articleMap.get(articleId);

                Map param = new HashMap();
                param.put("eqArticleId", articleId);
                article.getArticleThumbPictureList().addAll(this.articleThumbPictureDao.selectByMap(param, 1, 10, false));
                if (article.getPicFlag().equals(Constants.PIC_FLAG_HAVE_PIC)) {
                    param.put("orderByClause", "ORDER_NUM asc");
                    article.getArticlePictureList().addAll(this.articlePictureDao.selectByMap(param, 1, 1000, false));
                }
                result.add(article);
            }
        }
        return result;
    }


    /**
     * 插入文章图片
     * @param object
     */
    private void insertArticlePictureList( Article object ){
        for (ArticlePicture pic : object.getArticlePictureList()) {
            String hashCode = PictureUtil.getHashCodeFromUrl(pic.getPicUrl());
            if(!StringUtil.isEmpty(hashCode)){
                pic.setPicHashcode(hashCode);
                articlePictureDao.insert( pic.initWith( object ) );
            }
        }
    }
    /**
     * 更新文章图片
     * @param object
     */
    private void updateArticlePictureList( Article object ) {
        if(!object.getArticlePictureList().isEmpty()) {
            Map<String,Object> paramMap = new HashMap<String,Object>();
            paramMap.put("eqArticleId", object.getId());
            PageList<ArticlePicture> dbList = articlePictureDao.selectByMap(paramMap, 1, 1000, false);
            List<ArticlePicture> picList = object.getArticlePictureList();

            if(picList.isEmpty() && dbList.size()>0 ){   //清空数据库的内容
                articlePictureDao.deleteByMap(paramMap);
            }

            if(dbList.isEmpty()){
                insertArticlePictureList( object );
            }else{
                List<ArticlePicture> addList = new ArrayList<ArticlePicture>();
                List<ArticlePicture> updateList = new ArrayList<ArticlePicture>();
                List<ArticlePicture> deleteList = new ArrayList<ArticlePicture>();
                Map<String, ArticlePicture> map = new HashMap<String, ArticlePicture>();
                for(ArticlePicture articlePictureDB : dbList){
                    String picUrlDB = articlePictureDB.getPicUrl();
                    String hashCodeDB = PictureUtil.getHashCodeFromUrl(picUrlDB);
                    map.put(hashCodeDB, articlePictureDB);
                }
                Set<String> hashCodeSetDB = map.keySet();
                Set<String> hashCodeSet = new HashSet<String>();
                for(ArticlePicture articlePicture : picList){
                    String picUrl = articlePicture.getPicUrl();
                    String hashCode = PictureUtil.getHashCodeFromUrl(picUrl);
                    if(hashCodeSetDB.contains(hashCode)&&map.get(hashCode)!=null){
                        articlePicture.setId(map.get(hashCode).getId());
                        updateList.add(articlePicture);
                    }else{
                        addList.add(articlePicture);
                    }
                    hashCodeSet.add(hashCode);
                }

                for(ArticlePicture articlePictureDB : dbList){
                    String picUrlDB = articlePictureDB.getPicUrl();
                    String hashCodeDB = PictureUtil.getHashCodeFromUrl(picUrlDB);
                    if(!hashCodeSet.contains(hashCodeDB)){
                        deleteList.add(articlePictureDB);
                    }
                }

                for (ArticlePicture articlePicture : addList) {
                    if( !PictureUtil.isInPictureLib( articlePicture.getPicUrl() ) ){
                        continue;
                    }
                    articlePictureDao.insert(articlePicture.initWith(object));
                }
                for (ArticlePicture articlePicture : updateList) {
                    if( !PictureUtil.isInPictureLib(articlePicture.getPicUrl() ) ){
                        continue;
                    }
                    articlePictureDao.update(articlePicture.initWith(object));
                }
                for (ArticlePicture articlePicture : deleteList) {
                    articlePictureDao.deleteById(articlePicture.getId());
                }
            }
        }
    }

    /**
     * 插入文章图片
     * @param object
     */
    private void insertArticleThumbPicList( Article object ){
        for(ArticleThumbPicture articleThumbPicture : object.getArticleThumbPictureList()){
            String hashCode = PictureUtil.getHashCodeFromUrl(articleThumbPicture.getPicUrl());
            if(!StringUtil.isEmpty(hashCode)){
                articleThumbPicture.setPicHashcode(hashCode);
                articleThumbPictureDao.insert( articleThumbPicture.initWith( object ) );
            }
        }
    }
    /**
     * 更新缩略图
     * @param object
     */
    private void updateArticleThumbPicList( Article object ) {
        //数据库原有的文章图片
        Map<String,Object> paramMap = new HashMap<String,Object>();
        paramMap.put("eqArticleId", object.getId());
        PageList<ArticleThumbPicture> dbList = articleThumbPictureDao.selectByMap(paramMap, 1, 10, false);
        //文章缩略图
        List<ArticleThumbPicture> thumbPicList = object.getArticleThumbPictureList();

        if( thumbPicList.isEmpty() && dbList.size()>0 ){    //清空数据库的内容
            articleThumbPictureDao.deleteByMap(paramMap);
        }
        if(!thumbPicList.isEmpty()) {
            if(dbList.isEmpty()){
                insertArticleThumbPicList( object );
            }else{
                List<ArticleThumbPicture> addList = new ArrayList<ArticleThumbPicture>();
                List<ArticleThumbPicture> updateList = new ArrayList<ArticleThumbPicture>();
                List<ArticleThumbPicture> deleteList = new ArrayList<ArticleThumbPicture>();

                Map<String,ArticleThumbPicture> articleThumbPicMap = new HashMap<String,ArticleThumbPicture>();
                for(ArticleThumbPicture articleThumbPicDB : dbList){
                    String picUrlDB = articleThumbPicDB.getPicUrl();
                    String hashCodeDB = PictureUtil.getHashCodeFromUrl(picUrlDB);
                    articleThumbPicMap.put(hashCodeDB, articleThumbPicDB);
                }

                Set<String> hashCodeSet = new HashSet<String>();
                for(ArticleThumbPicture articleThumbPic : thumbPicList){
                    String picUrl = articleThumbPic.getPicUrl();
                    String hashCode = PictureUtil.getHashCodeFromUrl(picUrl);
                    if(articleThumbPicMap.keySet().contains(hashCode)){
                        articleThumbPic.setId(articleThumbPicMap.get(hashCode).getId());
                        updateList.add(articleThumbPic);
                    }else{
                        addList.add(articleThumbPic);
                    }
                    hashCodeSet.add(hashCode);
                }

                for(ArticleThumbPicture articleThumbPicDB : dbList){
                    String picUrlDB = articleThumbPicDB.getPicUrl();
                    String hashCodeDB = PictureUtil.getHashCodeFromUrl(picUrlDB);
                    if(!hashCodeSet.contains(hashCodeDB)){
                        deleteList.add(articleThumbPicDB);
                    }
                }

                for (ArticleThumbPicture thumbPic : addList) {
                    articleThumbPictureDao.insert(thumbPic.initWith(object));
                }
                for (ArticleThumbPicture thumbPic : updateList) {
                    articleThumbPictureDao.update(thumbPic.initWith(object));
                }
                for (ArticleThumbPicture thumbPic : deleteList) {
                    articleThumbPictureDao.deleteById(thumbPic.getId());
                }
            }
        }
    }

}